import { createRouter, createWebHistory } from 'vue-router'

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '登录', hideInMenu: true, requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: { title: '工作台首页', icon: 'dashboard' }
      },
      {
        path: '/archives',
        name: 'Archives',
        component: () => import('@/views/Archives/index.vue'),
        meta: { title: '生灵档案管理', icon: 'user' }
      },
      {
        path: '/archives/:id/basic',
        name: 'ArchiveBasicInfo',
        component: () => import('@/views/Archives/detail/BasicInfo.vue'),
        meta: { title: '个人基础信息', icon: 'user', parent: 'Archives' }
      },
      {
        path: '/archives/:id/life-history',
        name: 'ArchiveLifeHistory',
        component: () => import('@/views/Archives/detail/LifeHistory.vue'),
        meta: { title: '生命历程管理', icon: 'clock-circle', parent: 'Archives' }
      },
      {
        path: '/archives/:id/social-network',
        name: 'ArchiveSocialNetwork',
        component: () => import('@/views/Archives/detail/SocialNetwork.vue'),
        meta: { title: '社会关系网络', icon: 'team', parent: 'Archives' }
      },
      {
        path: '/archives/:id/archive-info',
        name: 'ArchiveInfo',
        component: () => import('@/views/Archives/detail/ArchiveInfo.vue'),
        meta: { title: '档案信息', icon: 'folder', parent: 'Archives' }
      },
      {
        path: '/life-death',
        name: 'LifeDeath',
        component: () => import('@/views/LifeDeath/index.vue'),
        meta: { title: '寿命与生死管理', icon: 'clock-circle' }
      },
      {
        path: '/karma',
        name: 'Karma',
        component: () => import('@/views/Karma/index.vue'),
        meta: { title: '因果业力系统', icon: 'trophy' }
      },
      {
        path: '/karma/good-deeds',
        name: 'KarmaGoodDeeds',
        component: () => import('@/views/Karma/GoodDeeds.vue'),
        meta: { title: '善行记录管理', icon: 'smile', parent: 'Karma' }
      },
      {
        path: '/karma/bad-deeds',
        name: 'KarmaBadDeeds',
        component: () => import('@/views/Karma/BadDeeds.vue'),
        meta: { title: '恶行记录管理', icon: 'frown', parent: 'Karma' }
      },
      {
        path: '/karma/engine',
        name: 'KarmaEngine',
        component: () => import('@/views/Karma/Engine.vue'),
        meta: { title: '业力计算引擎', icon: 'thunderbolt', parent: 'Karma' }
      },
      {
        path: '/reincarnation',
        name: 'Reincarnation',
        component: () => import('@/views/Reincarnation/index.vue'),
        meta: { title: '轮回转世系统', icon: 'reload' }
      },
      {
        path: '/reincarnation/rules',
        name: 'ReincarnationRules',
        component: () => import('@/views/Reincarnation/Rules.vue'),
        meta: { title: '转世规则管理', icon: 'setting', parent: 'Reincarnation' }
      },
      {
        path: '/reincarnation/history',
        name: 'ReincarnationHistory',
        component: () => import('@/views/Reincarnation/History.vue'),
        meta: { title: '轮回历史记录', icon: 'history', parent: 'Reincarnation' }
      },
      {
        path: '/reincarnation/arrangement',
        name: 'ReincarnationArrangement',
        component: () => import('@/views/Reincarnation/Arrangement.vue'),
        meta: { title: '投胎安排管理', icon: 'calendar', parent: 'Reincarnation' }
      },
      {
        path: '/judgment',
        name: 'Judgment',
        component: () => import('@/views/Judgment/index.vue'),
        meta: { title: '地府审判系统', icon: 'bank' }
      },
      {
        path: '/judgment/pending-cases',
        name: 'JudgmentPendingCases',
        component: () => import('@/views/Judgment/PendingCases.vue'),
        meta: { title: '待审案件管理', icon: 'clock-circle', parent: 'Judgment' }
      },
      {
        path: '/judgment/process',
        name: 'JudgmentProcess',
        component: () => import('@/views/Judgment/JudgmentProcess.vue'),
        meta: { title: '审判流程管理', icon: 'setting', parent: 'Judgment' }
      },
      {
        path: '/judgment/punishment',
        name: 'JudgmentPunishment',
        component: () => import('@/views/Judgment/PunishmentExecution.vue'),
        meta: { title: '刑罚执行系统', icon: 'thunderbolt', parent: 'Judgment' }
      },
      {
        path: '/salvation',
        name: 'Salvation',
        component: () => import('@/views/Salvation/index.vue'),
        meta: { title: '超度与救赎', icon: 'heart' }
      },
      // 超度申请管理子路由
      {
        path: '/salvation/transcendence-application',
        name: 'SalvationTranscendenceApplication',
        component: () => import('@/views/Salvation/TranscendenceApplication.vue'),
        meta: { title: '超度申请管理', icon: 'heart', parent: 'Salvation' }
      },
      {
        path: '/salvation/transcendence-application/process',
        name: 'TranscendenceApplicationProcess',
        component: () => import('@/views/Salvation/transcendence/ApplicationProcess.vue'),
        meta: { title: '超度申请流程', icon: 'form', parent: 'SalvationTranscendenceApplication' }
      },
      {
        path: '/salvation/transcendence-application/qualification',
        name: 'TranscendenceApplicationQualification',
        component: () => import('@/views/Salvation/transcendence/QualificationReview.vue'),
        meta: { title: '申请资格审核', icon: 'user', parent: 'SalvationTranscendenceApplication' }
      },
      {
        path: '/salvation/transcendence-application/ritual',
        name: 'TranscendenceApplicationRitual',
        component: () => import('@/views/Salvation/transcendence/RitualArrangement.vue'),
        meta: { title: '超度仪式安排', icon: 'calendar', parent: 'SalvationTranscendenceApplication' }
      },
      {
        path: '/salvation/transcendence-application/evaluation',
        name: 'TranscendenceApplicationEvaluation',
        component: () => import('@/views/Salvation/transcendence/EffectEvaluation.vue'),
        meta: { title: '超度效果评估', icon: 'line-chart', parent: 'SalvationTranscendenceApplication' }
      },
      // 功德转移系统子路由
      {
        path: '/salvation/merit-transfer',
        name: 'SalvationMeritTransfer',
        component: () => import('@/views/Salvation/MeritTransfer.vue'),
        meta: { title: '功德转移系统', icon: 'trophy', parent: 'Salvation' }
      },
      {
        path: '/salvation/merit-transfer/source',
        name: 'MeritTransferSource',
        component: () => import('@/views/Salvation/merit/SourceManagement.vue'),
        meta: { title: '功德来源管理', icon: 'gold', parent: 'SalvationMeritTransfer' }
      },
      {
        path: '/salvation/merit-transfer/rules',
        name: 'MeritTransferRules',
        component: () => import('@/views/Salvation/merit/TransferRules.vue'),
        meta: { title: '功德转移规则', icon: 'setting', parent: 'SalvationMeritTransfer' }
      },
      {
        path: '/salvation/merit-transfer/records',
        name: 'MeritTransferRecords',
        component: () => import('@/views/Salvation/merit/UsageRecords.vue'),
        meta: { title: '功德使用记录', icon: 'history', parent: 'SalvationMeritTransfer' }
      },
      {
        path: '/salvation/merit-transfer/balance',
        name: 'MeritTransferBalance',
        component: () => import('@/views/Salvation/merit/BalanceQuery.vue'),
        meta: { title: '功德余额查询', icon: 'search', parent: 'SalvationMeritTransfer' }
      },
      // 救赎计划管理子路由
      {
        path: '/salvation/redemption-plan',
        name: 'SalvationRedemptionPlan',
        component: () => import('@/views/Salvation/RedemptionPlan.vue'),
        meta: { title: '救赎计划管理', icon: 'gift', parent: 'Salvation' }
      },
      {
        path: '/salvation/redemption-plan/tasks',
        name: 'RedemptionPlanTasks',
        component: () => import('@/views/Salvation/redemption/TaskSetting.vue'),
        meta: { title: '救赎任务设置', icon: 'setting', parent: 'SalvationRedemptionPlan' }
      },
      {
        path: '/salvation/redemption-plan/progress',
        name: 'RedemptionPlanProgress',
        component: () => import('@/views/Salvation/redemption/ProgressTracking.vue'),
        meta: { title: '救赎进度跟踪', icon: 'line-chart', parent: 'SalvationRedemptionPlan' }
      },
      {
        path: '/salvation/redemption-plan/rewards',
        name: 'RedemptionPlanRewards',
        component: () => import('@/views/Salvation/redemption/SuccessRewards.vue'),
        meta: { title: '救赎成功奖励', icon: 'gift', parent: 'SalvationRedemptionPlan' }
      },
      {
        path: '/salvation/redemption-plan/failure',
        name: 'RedemptionPlanFailure',
        component: () => import('@/views/Salvation/redemption/FailureHandling.vue'),
        meta: { title: '救赎失败处理', icon: 'stop', parent: 'SalvationRedemptionPlan' }
      },
      {
        path: '/statistics',
        name: 'Statistics',
        component: () => import('@/views/Statistics/index.vue'),
        meta: { title: '统计分析中心', icon: 'bar-chart' }
      },
      // 统计分析中心子路由
      // 7.1 生死数据统计
      {
        path: '/statistics/life-death-trend',
        name: 'StatisticsLifeDeathTrend',
        component: () => import('@/views/Statistics/LifeDeathTrend.vue'),
        meta: { title: '死亡率趋势分析', icon: 'line-chart', parent: 'Statistics' }
      },
      {
        path: '/statistics/death-cause',
        name: 'StatisticsDeathCause',
        component: () => import('@/views/Statistics/DeathCause.vue'),
        meta: { title: '死因分类统计', icon: 'pie-chart', parent: 'Statistics' }
      },
      {
        path: '/statistics/age-distribution',
        name: 'StatisticsAgeDistribution',
        component: () => import('@/views/Statistics/AgeDistribution.vue'),
        meta: { title: '年龄分布分析', icon: 'bar-chart', parent: 'Statistics' }
      },
      {
        path: '/statistics/regional-comparison',
        name: 'StatisticsRegionalComparison',
        component: () => import('@/views/Statistics/RegionalComparison.vue'),
        meta: { title: '地区死亡对比', icon: 'global', parent: 'Statistics' }
      },
      // 7.2 业力分析报表
      {
        path: '/statistics/karma-ratio',
        name: 'StatisticsKarmaRatio',
        component: () => import('@/views/Statistics/KarmaRatio.vue'),
        meta: { title: '善恶比例统计', icon: 'trophy', parent: 'Statistics' }
      },
      {
        path: '/statistics/karma-distribution',
        name: 'StatisticsKarmaDistribution',
        component: () => import('@/views/Statistics/KarmaDistribution.vue'),
        meta: { title: '业力分布图表', icon: 'radar-chart', parent: 'Statistics' }
      },
      {
        path: '/statistics/moral-trend',
        name: 'StatisticsMoralTrend',
        component: () => import('@/views/Statistics/MoralTrend.vue'),
        meta: { title: '道德水平趋势', icon: 'rise', parent: 'Statistics' }
      },
      {
        path: '/statistics/social-climate',
        name: 'StatisticsSocialClimate',
        component: () => import('@/views/Statistics/SocialClimate.vue'),
        meta: { title: '社会风气分析', icon: 'team', parent: 'Statistics' }
      },
      // 7.3 轮回数据分析
      {
        path: '/statistics/reincarnation-success',
        name: 'StatisticsReincarnationSuccess',
        component: () => import('@/views/Statistics/ReincarnationSuccess.vue'),
        meta: { title: '转世成功率', icon: 'reload', parent: 'Statistics' }
      },
      {
        path: '/statistics/six-realms',
        name: 'StatisticsSixRealms',
        component: () => import('@/views/Statistics/SixRealms.vue'),
        meta: { title: '六道分布统计', icon: 'stock', parent: 'Statistics' }
      },
      {
        path: '/statistics/cultivation-progress',
        name: 'StatisticsCultivationProgress',
        component: () => import('@/views/Statistics/CultivationProgress.vue'),
        meta: { title: '修行进度报告', icon: 'fund', parent: 'Statistics' }
      },
      {
        path: '/statistics/reincarnation-efficiency',
        name: 'StatisticsReincarnationEfficiency',
        component: () => import('@/views/Statistics/ReincarnationEfficiency.vue'),
        meta: { title: '轮回效率分析', icon: 'dashboard', parent: 'Statistics' }
      },
      {
        path: '/management',
        name: 'Management',
        component: () => import('@/views/Management/index.vue'),
        meta: { title: '机构管理', icon: 'apartment' }
      },
      // 8.1 仙官职位管理
      {
        path: '/management/official-position',
        name: 'ManagementOfficialPosition',
        component: () => import('@/views/Management/OfficialPosition/index.vue'),
        meta: { title: '仙官职位管理', icon: 'crown', parent: 'Management' }
      },
      {
        path: '/management/official-position/level-setting',
        name: 'OfficialPositionLevelSetting',
        component: () => import('@/views/Management/OfficialPosition/LevelSetting.vue'),
        meta: { title: '职位等级设置', icon: 'rise', parent: 'ManagementOfficialPosition' }
      },
      {
        path: '/management/official-position/permission-allocation',
        name: 'OfficialPositionPermissionAllocation',
        component: () => import('@/views/Management/OfficialPosition/PermissionAllocation.vue'),
        meta: { title: '权限分配管理', icon: 'safety', parent: 'ManagementOfficialPosition' }
      },
      {
        path: '/management/official-position/transfer-record',
        name: 'OfficialPositionTransferRecord',
        component: () => import('@/views/Management/OfficialPosition/TransferRecord.vue'),
        meta: { title: '职位调动记录', icon: 'swap', parent: 'ManagementOfficialPosition' }
      },
      {
        path: '/management/official-position/assessment-system',
        name: 'OfficialPositionAssessmentSystem',
        component: () => import('@/views/Management/OfficialPosition/AssessmentSystem.vue'),
        meta: { title: '考核评估系统', icon: 'star', parent: 'ManagementOfficialPosition' }
      },
      // 8.2 部门协作管理
      {
        path: '/management/department-cooperation',
        name: 'ManagementDepartmentCooperation',
        component: () => import('@/views/Management/DepartmentCooperation/index.vue'),
        meta: { title: '部门协作管理', icon: 'team', parent: 'Management' }
      },
      {
        path: '/management/department-cooperation/ten-courts-division',
        name: 'DepartmentCooperationTenCourtsDivision',
        component: () => import('@/views/Management/DepartmentCooperation/TenCourtsDivision.vue'),
        meta: { title: '十殿阎王分工', icon: 'bank', parent: 'ManagementDepartmentCooperation' }
      },
      {
        path: '/management/department-cooperation/coordination',
        name: 'DepartmentCooperationCoordination',
        component: () => import('@/views/Management/DepartmentCooperation/Coordination.vue'),
        meta: { title: '部门间协调', icon: 'cluster', parent: 'ManagementDepartmentCooperation' }
      },
      {
        path: '/management/department-cooperation/workflow-setting',
        name: 'DepartmentCooperationWorkflowSetting',
        component: () => import('@/views/Management/DepartmentCooperation/WorkflowSetting.vue'),
        meta: { title: '工作流程设置', icon: 'flow', parent: 'ManagementDepartmentCooperation' }
      },
      {
        path: '/management/department-cooperation/task-allocation',
        name: 'DepartmentCooperationTaskAllocation',
        component: () => import('@/views/Management/DepartmentCooperation/TaskAllocation.vue'),
        meta: { title: '任务分配系统', icon: 'inbox', parent: 'ManagementDepartmentCooperation' }
      },
      // 8.3 值班排班系统
      {
        path: '/management/duty-schedule',
        name: 'ManagementDutySchedule',
        component: () => import('@/views/Management/DutySchedule/index.vue'),
        meta: { title: '值班排班系统', icon: 'schedule', parent: 'Management' }
      },
      {
        path: '/management/duty-schedule/time-arrangement',
        name: 'DutyScheduleTimeArrangement',
        component: () => import('@/views/Management/DutySchedule/TimeArrangement.vue'),
        meta: { title: '值班时间安排', icon: 'clock-circle', parent: 'ManagementDutySchedule' }
      },
      {
        path: '/management/duty-schedule/personnel-allocation',
        name: 'DutySchedulePersonnelAllocation',
        component: () => import('@/views/Management/DutySchedule/PersonnelAllocation.vue'),
        meta: { title: '值班人员分配', icon: 'user', parent: 'ManagementDutySchedule' }
      },
      {
        path: '/management/duty-schedule/record-management',
        name: 'DutyScheduleRecordManagement',
        component: () => import('@/views/Management/DutySchedule/RecordManagement.vue'),
        meta: { title: '值班记录管理', icon: 'file-text', parent: 'ManagementDutySchedule' }
      },
      {
        path: '/management/duty-schedule/emergency-shift',
        name: 'DutyScheduleEmergencyShift',
        component: () => import('@/views/Management/DutySchedule/EmergencyShift.vue'),
        meta: { title: '紧急调班处理', icon: 'alert', parent: 'ManagementDutySchedule' }
      },
      {
        path: '/files',
        name: 'Files',
        component: () => import('@/views/Files/index.vue'),
        meta: { title: '档案文件管理', icon: 'folder' }
      },
      // 9.1 纸质档案数字化
      {
        path: '/files/digital-archive',
        name: 'FilesDigitalArchive',
        component: () => import('@/views/Files/DigitalArchive/index.vue'),
        meta: { title: '纸质档案数字化', icon: 'scan', parent: 'Files' }
      },
      {
        path: '/files/digital-archive/scan-management',
        name: 'DigitalArchiveScanManagement',
        component: () => import('@/views/Files/DigitalArchive/ScanManagement.vue'),
        meta: { title: '扫描文件管理', icon: 'scan', parent: 'FilesDigitalArchive' }
      },
      {
        path: '/files/digital-archive/ocr-recognition',
        name: 'DigitalArchiveOcrRecognition',
        component: () => import('@/views/Files/DigitalArchive/OcrRecognition.vue'),
        meta: { title: 'OCR文字识别', icon: 'eye', parent: 'FilesDigitalArchive' }
      },
      {
        path: '/files/digital-archive/classification',
        name: 'DigitalArchiveClassification',
        component: () => import('@/views/Files/DigitalArchive/Classification.vue'),
        meta: { title: '档案分类整理', icon: 'appstore', parent: 'FilesDigitalArchive' }
      },
      {
        path: '/files/digital-archive/tag-setting',
        name: 'DigitalArchiveTagSetting',
        component: () => import('@/views/Files/DigitalArchive/TagSetting.vue'),
        meta: { title: '检索标签设置', icon: 'tags', parent: 'FilesDigitalArchive' }
      },
      // 9.2 电子档案管理
      {
        path: '/files/electronic-archive',
        name: 'FilesElectronicArchive',
        component: () => import('@/views/Files/ElectronicArchive/index.vue'),
        meta: { title: '电子档案管理', icon: 'laptop', parent: 'Files' }
      },
      {
        path: '/files/electronic-archive/version-control',
        name: 'ElectronicArchiveVersionControl',
        component: () => import('@/views/Files/ElectronicArchive/VersionControl.vue'),
        meta: { title: '文件版本控制', icon: 'branches', parent: 'FilesElectronicArchive' }
      },
      {
        path: '/files/electronic-archive/access-permission',
        name: 'ElectronicArchiveAccessPermission',
        component: () => import('@/views/Files/ElectronicArchive/AccessPermission.vue'),
        meta: { title: '访问权限设置', icon: 'lock', parent: 'FilesElectronicArchive' }
      },
      {
        path: '/files/electronic-archive/backup-recovery',
        name: 'ElectronicArchiveBackupRecovery',
        component: () => import('@/views/Files/ElectronicArchive/BackupRecovery.vue'),
        meta: { title: '备份恢复系统', icon: 'cloud-upload', parent: 'FilesElectronicArchive' }
      },
      {
        path: '/files/electronic-archive/security-encryption',
        name: 'ElectronicArchiveSecurityEncryption',
        component: () => import('@/views/Files/ElectronicArchive/SecurityEncryption.vue'),
        meta: { title: '安全加密保护', icon: 'safety', parent: 'FilesElectronicArchive' }
      },
      // 9.3 档案借阅系统
      {
        path: '/files/borrow-system',
        name: 'FilesBorrowSystem',
        component: () => import('@/views/Files/BorrowSystem/index.vue'),
        meta: { title: '档案借阅系统', icon: 'audit', parent: 'Files' }
      },
      {
        path: '/files/borrow-system/borrow-process',
        name: 'BorrowSystemBorrowProcess',
        component: () => import('@/views/Files/BorrowSystem/BorrowProcess.vue'),
        meta: { title: '借阅申请流程', icon: 'form', parent: 'FilesBorrowSystem' }
      },
      {
        path: '/files/borrow-system/term-management',
        name: 'BorrowSystemTermManagement',
        component: () => import('@/views/Files/BorrowSystem/TermManagement.vue'),
        meta: { title: '借阅期限管理', icon: 'calendar', parent: 'FilesBorrowSystem' }
      },
      {
        path: '/files/borrow-system/return-reminder',
        name: 'BorrowSystemReturnReminder',
        component: () => import('@/views/Files/BorrowSystem/ReturnReminder.vue'),
        meta: { title: '归还提醒功能', icon: 'bell', parent: 'FilesBorrowSystem' }
      },
      {
        path: '/files/borrow-system/damage-compensation',
        name: 'BorrowSystemDamageCompensation',
        component: () => import('@/views/Files/BorrowSystem/DamageCompensation.vue'),
        meta: { title: '损坏赔偿处理', icon: 'exclamation-circle', parent: 'FilesBorrowSystem' }
      },

      // 个人信息管理
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/Profile/index.vue'),
        meta: { title: '个人信息', icon: 'user', hideInMenu: true }
      },

      // 系统设置
      {
        path: '/settings',
        name: 'Settings',
        component: () => import('@/views/Settings/index.vue'),
        meta: { title: '系统设置', icon: 'setting', hideInMenu: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '仙官登录' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404/index.vue'),
    meta: { title: '页面未找到', requiresAuth: false }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 生死簿管理系统` : '生死簿管理系统'

  // 获取登录状态
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token

  // 如果访问登录页
  if (to.path === '/login') {
    if (isLoggedIn) {
      // 已登录则重定向到首页
      next('/')
    } else {
      // 未登录可以访问登录页
      next()
    }
    return
  }

  // 如果访问需要登录的页面
  if (to.meta?.requiresAuth !== false) {
    if (!isLoggedIn) {
      // 未登录则重定向到登录页
      next('/login')
    } else {
      // 已登录可以访问
      next()
    }
  } else {
    // 不需要登录验证的页面
    next()
  }
})

export default router
